<?php

namespace App\Http\Controllers\API\Systems;

use DB;
use Config;
use Hash;
use App\Http\Controllers\API\ApiController;
use Ramsey\Uuid\Uuid;
use App\Eloqumd\System\PlateUser;
use Illuminate\Http\Request;
use App\Validate\System\SystemValidator;

class PlateUserController extends ApiController
{
    // 获取平台下用户
    public function getPlatformUserList(Request $request)
    {
        $page = (int)$request->input('page/d', 1) - 1;
        $limit = $request->input('limit/d', $this->limit);
        $keyword = $request->input('keyword', '');

        $where = null;
        // 快捷搜索-用户名，真实姓名-手机号
        if ($keyword) {
            $where[] = ['user_name', 'like', "%{$keyword}%", 'OR'];
            $where[] = ['user_real_name', 'like', "%{$keyword}%", 'OR'];
            $where[] = ['user_phone', 'like', "%{$keyword}%", 'OR'];
        }

        if ($this->apiUser['user_type'] != 0) {
            $where[] = ['user_plate', '=', $this->apiUser['user_plate'], 'AND'];
        } else {
            $where[] = ['user_type', '<>', 0, 'AND'];
        }

        $totalCount = PlateUser::where($where)->count();
        $listData = PlateUser::where($where)
            ->select(['id', 'user_plate', 'user_name', 'user_real_name', 'user_phone', 'user_email', 'created_at', 'user_status', 'user_type'])
            ->offset($page)
            ->limit($limit)
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list', trans('alg.Browse-Platform-User-List-Info'));
    }

    // 根据用户ID获取用户信息
    public function getPlatformUserInfoById(Request $request)
    {
        $userId = $request->input('id', 0);
        $userInfo = PlateUser::find($userId)->toArray();
        // 剔除隐患字段
        unset($userInfo['user_pass']);
        unset($userInfo['user_solt']);

        return $this->jsonReturns(
            10000,
            $this->success,
            $userInfo,
            'get',
            trans('alg.Get-Browse-Platform-User-Info', ['name' => $userInfo['user_real_name'], 'id' => $userId])
        );
    }

    // 创建用户
    public function platformUserCreated(Request $request)
    {
        // 数据校验
        $param = $request->all();
        if (true !== $validateRes = SystemValidator::platformUserCreated($param)) {
            return $this->jsonReturns(99999, $validateRes, [], 'create/verror', trans('alg.Create-Platform-User-And-Validate-Error'));
        }

        // 数据处理
        DB::beginTransaction();
        try {
            $model = new PlateUser;
            $model->user_plate = $this->apiUser['user_plate'];
            $model->user_name = $param['user_name'] ?? '';
            $initPwd = Config::get('api.init_common_pwd');
            $userSolt = Uuid::uuid1()->getHex();
            $model->user_solt = $userSolt;
            $model->user_pass = Hash::make($initPwd, ['solt' => $userSolt]);
            $model->user_real_name = $param['user_real_name'];
            $model->user_phone = $param['user_phone'];
            $model->user_email = $param['user_email'];
            $model->user_type = 2;
            $model->user_status = 1;
            $model->created_at = date('Y-m-d H:i:s');
            $model->save();

            DB::commit();
            
            // 邮件通知激活账号
            // MailSendController::Mail(PlateUser::select(['user_real_name', 'user_email'])->find($model->id));
            
            return $this->jsonReturns(
                10000,
                $this->success,
                [],
                'create',
                trans('alg.Create-Platform-User-Success', [
                    'name' => $param['user_real_name']
                ])
            );
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'create/error', trans('alg.Create-Platform-User-System-Error'));
        }
    }

    // 启用禁用用户
    public function platformUserStatused(Request $request)
    {
        // 数据校验
        $id = $request->input('id', 0);
        $user_status = $request->input('user_status', '');
        if (!$id || $user_status == '') {
            return $this->jsonReturns(99999, trans('alg.Illegal-Parameter', ['p' => 'id/user_status']), [], 'status/verror', trans('alg.Status-Platform-User-And-Validate-Error'));
        }

        // 数据处理
        DB::beginTransaction();
        try {
            $model = PlateUser::find($id);
            $model->user_status = $user_status;
            $model->save();

            DB::commit();

            return $this->jsonReturns(
                10000,
                $this->success,
                [],
                'status',
                trans('alg.Status-Platform-User-Success', [
                    'name' => $model->user_real_name,
                    'status' => ($user_status == 1 ? trans('alg.Enabled') : trans('alg.Disabled'))
                ])
            );
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'status/error', trans('alg.Status-Platform-User-System-Error'));
        }
    }

    // 重置密码
    public function platformUserResetPwd(Request $request)
    {
        $id = $request->input('id', 0);
        if (!$id) {
            return $this->jsonReturns(99999, trans('alg.Illegal-Parameter', ['p' => 'id']), [], 'reset/verror', trans('alg.Reset-Pwd-Platform-User-And-Validate-Error'));
        }

        DB::beginTransaction();
        try {
            $model = PlateUser::find($id);
            $initPwd = Config::get('api.init_common_pwd');
            $userSolt = Uuid::uuid1()->getHex();
            $model->user_solt = $userSolt;
            $model->user_pass = Hash::make($initPwd, ['solt' => $userSolt]);

            $model->save();
            DB::commit();

            return $this->jsonReturns(
                10000,
                $this->success,
                [],
                'reset',
                trans('alg.Reset-Pwd-Platform-User-Success', [
                    'name' => $model->user_real_name
                ])
            );
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'reset/error', trans('alg.Reset-Pwd-Platform-User-System-Error'));
        }
    }
}
